'use strict';

import React, {Component, PropTypes} from 'react';
import {StyleSheet, View, Text, PanResponder, Dimensions, TouchableOpacity} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import values from 'lodash/values';
import keys from 'lodash/keys';
import {fetchScenesInfo, deleteScence, sortScenes} from '../action/girlAction';
import assign from 'lodash/assign';
import {MtSeparator, MtListView} from 'martian-ui';
import NavigationBar from '../components/common/NavigationBar'
import UpdateSence from '../container/UpdateSence';
import BoxShadowYaGuan from '../components/common/BoxShadowYaGuan'

const EntityLabels = require('../constants/entities');
const width = Dimensions.get('window').width;

function _renderRow(scence, sectionID, rowID) {
  const {navigator, gatewayId} = this.props;
  return (
    <TouchableOpacity
      onPress={() => {
        navigator.push({
          component: UpdateSence,
          params: {
            scenceId: scence.id,
            navigator: navigator,
            gatewayId
          },
        })
      }}
    >
      <View style={{backgroundColor: '#fff', flex: 1, height: 46, justifyContent: 'center',}}>
        <Text style={styles.itemTitle}>{scence.name}</Text>
      </View>
      <MtSeparator style={{marginLeft: 15}}/>
    </TouchableOpacity>
  );
}

class AllScence extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: [],
      order: [],
      setting: false,
    }
  }

  componentDidMount() {
    this.refresh()

  }

  refresh() {
    const {fetchScenesInfo, gatewayId} = this.props;
    fetchScenesInfo(gatewayId);
  }

  convertPropsToStates(props) {
    const {scenesEntities, roomId} = props;


    const scenceList = scenesEntities && values(scenesEntities).sort((ele1, ele2) => {
      return ele1['inRoomSort'] - ele2['inRoomSort'];
    }).filter(ele => ele.roomId === roomId);
    const newState = assign({
      scenceList,


    });

    if (newState) {
      this.setState(newState);
    }
  }

  componentWillReceiveProps(nextProps) {
    this.convertPropsToStates((nextProps));
  }

  _deleteRow(item) {
    const {scenceList} = this.state;
    const {deleteScence, accessToken} = this.props;
    deleteScence(item.id, accessToken).then(
      () => {
        console.warn(222)
      }
    );
    this.setState({
      scenceList: scenceList.filter((ele) => ele.id !== item.id)
    })
  }

  render() {
    const {navigator} = this.props;
    const {setting, scenceList} = this.state;
    const rightButton = setting ?
      <TouchableOpacity onPress={() => this.setState({setting: !setting})}><Text
        style={{fontSize: 16, color: '#333333'}}>完成</Text></TouchableOpacity> :
      <Icon name="ios-remove-circle" size={25} color="#FF151C" onPress={() => this.setState({setting: !setting})}/>
    const renderRowBind = _renderRow.bind(this);
    return (
      <View style={styles.container}>
        <NavigationBar
          title={'编辑场景'}
          statusBar={{backgroundColor: '#ffffff', barStyle: 'dark-content'}}
          navigator={navigator}
          rightButton={rightButton}
          style={{borderBottomWidth: 1, borderColor: '#EDEDED', backgroundColor: '#ffffff'}}
        />
        {setting ? (
          scenceList.map((item, i) => {
            this.state.order.push(item);
            return (
              <View
                {...this._panResponder.panHandlers}
                ref={(ref) => this.state.items[i] = ref}
                key={i}
                style={[styles.item, {top: (i + 1) * 49}]}>
                <TouchableOpacity onPress={() => this._deleteRow(item)}
                >
                  <BoxShadowYaGuan
                    width={41}
                    height={68}
                    renderItem={() => {
                      return (
                        <View style={styles.deleteView}>
                          <Icon name="ios-remove-circle" size={25} color="#FF151C"/>
                        </View>
                      )
                    }}
                  />
                </TouchableOpacity>
                <BoxShadowYaGuan
                  width={width - 86}
                  height={68}
                  renderItem={() => {
                    return (
                      <View style={styles.scenceItem}>
                        <Text style={styles.itemTitle}>{item.name}</Text>
                      </View>
                    )
                  }}
                />
              </View>
            );
          })
        ) : (
          <MtListView
            data={scenceList}
            renderRow={renderRowBind}
            initialListSize={100}
            scrollRenderAheadDistance={500}
            onEndReachedThreshold={10}
            renderSeparator={undefined}
            enableEmptySections={true}
            removeClippedSubviews={false}
            onRefresh={() => {
              this.refresh();
            }}
            onEndReached={() => {

            }}
          />
        )}

      </View>
    );
  }

  componentWillMount() {
    const {accessToken} = this.props;
    this.convertPropsToStates(this.props);
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onMoveShouldSetPanResponder: (evt, gestureState) => true,
      onPanResponderGrant: (evt, gestureState) => {
        const {pageY, locationY} = evt.nativeEvent;
        this.index = this._getIdByPosition(pageY);
        this.preY = pageY - locationY;
        //get the taped item and highlight it
        let item = this.state.items[this.index];
        item.setNativeProps({
          style: {
            shadowColor: "#000",
            shadowOpacity: 0.3,
            shadowRadius: 5,
            shadowOffset: {height: 0, width: 2},
            elevation: 5
          }
        });
      },
      onPanResponderMove: (evt, gestureState) => {
        let top = this.preY + gestureState.dy;
        let item = this.state.items[this.index];
        item.setNativeProps({
          style: {top: top}
        });

        let collideIndex = this._getIdByPosition(evt.nativeEvent.pageY);
        if (collideIndex !== this.index && collideIndex !== -1) {
          let collideItem = this.state.items[collideIndex];
          collideItem && collideItem.setNativeProps({
            style: {top: this._getTopValueYById(this.index)}
          });
          //swap two values
          [this.state.items[this.index], this.state.items[collideIndex]] = [this.state.items[collideIndex], this.state.items[this.index]];
          [this.state.order[this.index], this.state.order[collideIndex]] = [this.state.order[collideIndex], this.state.order[this.index]];
          this.index = collideIndex;
        }
      },
      onPanResponderTerminationRequest: (evt, gestureState) => true,
      onPanResponderRelease: (evt, gestureState) => {
        const {sortScenes, productKey, deviceName} = this.props;
        const shadowStyle = {
          shadowColor: "#000",
          shadowOpacity: 0,
          shadowRadius: 0,
          shadowOffset: {height: 0, width: 0,},
          elevation: 0
        };
        let item = this.state.items[this.index];
        //go back the correct position
        item.setNativeProps({
          style: {...shadowStyle, top: this._getTopValueYById(this.index)}
        });
        if (this.state.order.length > 0) {
          const sortIds = this.state.order;
          console.warn(this.state.order)
          sortScenes(this.state.order, accessToken);
        }


      },
      onPanResponderTerminate: (evt, gestureState) => {
        // Another component has become the responder, so this gesture
        // should be cancelled
      }
    });
  }

  _getIdByPosition(pageY) {
    var id = -1;
    const height = 49;

    if (pageY >= height && pageY < height * 2)
      id = 0;
    else if (pageY >= height * 2 && pageY < height * 3)
      id = 1;
    else if (pageY >= height * 3 && pageY < height * 4)
      id = 2;
    else if (pageY >= height * 4 && pageY < height * 5)
      id = 3;
    else if (pageY >= height * 5 && pageY < height * 6)
      id = 4;
    else if (pageY >= height * 6 && pageY < height * 7)
      id = 5;
    else if (pageY >= height * 7 && pageY < height * 8)
      id = 6;
    else if (pageY >= height * 8 && pageY < height * 9)
      id = 7;
    else if (pageY >= height * 9 && pageY < height * 10)
      id = 8;
    else if (pageY >= height * 10 && pageY < height * 11)
      id = 9;
    else if (pageY >= height * 11 && pageY < height * 12)
      id = 10;
    else if (pageY >= height * 12 && pageY < height * 13)
      id = 11;
    else if (pageY >= height * 13 && pageY < height * 14)
      id = 12;
    else if (pageY >= height * 14 && pageY < height * 15)
      id = 13;
    else if (pageY >= height * 15 && pageY < height * 16)
      id = 14;
    else if (pageY >= height * 16 && pageY < height * 17)
      id = 15;
    else if (pageY >= height * 17 && pageY < height * 18)
      id = 16;
    else if (pageY >= height * 18 && pageY < height * 19)
      id = 17;
    else if (pageY >= height * 19 && pageY < height * 20)
      id = 18;
    else if (pageY >= height * 20 && pageY < height * 21)
      id = 19;

    return id;
  }

  _getTopValueYById(id) {
    const height = 49;
    return (id + 1) * height;
  }
}

function mappingStateToProps(state, ownProps) {
  const entities = state['entities'];
  const scenesEntities = entities[EntityLabels.scenes];

  const assessTokenEntity = entities[EntityLabels.token];
  const assessToken = assessTokenEntity && values(assessTokenEntity)[0].assessToken;

  return {
    scenesEntities,
    assessToken,


  };
}

function mapDispatchToProps(dispatch) {
  const actions = {
    fetchScenesInfo,
    deleteScence,
    sortScenes
  };
  return bindActionCreators(actions, dispatch);
}

export default connect(mappingStateToProps, mapDispatchToProps)(AllScence);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F4F4F4',
  },
  item: {
    flexDirection: 'row',
    height: 49,
    width: width,
    alignItems: 'center',
    marginTop: 15,
    paddingLeft: 20,
    position: 'absolute',
  },
  itemTitle: {
    fontSize: 15,
    color: '#000',
    marginLeft: 20
  },
  deleteView: {
    width: 41,
    height: 68,
    backgroundColor: '#FFFFFF',
    marginRight: 15,
    justifyContent: 'center',
    alignItems: 'center',
  },
  scenceItem: {
    flex: 1,
    height: 68,
    justifyContent: 'center',
    backgroundColor: '#fff',
  }
});
